﻿using System;
using System.Configuration;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using Channelvn.Cached.Common;

namespace Channelvn.Cached.UrlRewrite
{
    public class RewriteModule : IHttpHandlerFactory, IRequiresSessionState
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url1, string pathTranslated)
        {
            if (HttpContext.Current.Request.Url.Query != String.Empty)
            {
                if (context.Request.Url.Query.Length > 0)
                {
                    context.Items["VirtualUrl"] = context.Request.Path + context.Request.Url.Query;
                }
            }
            if (context.Items["VirtualUrl"] == null)
            {
                context.Items["VirtualUrl"] = context.Request.Path;
            }

            string url = context.Request.Url.AbsolutePath;
            string rewrite = "";

            _301Redirection _301 = new _301Redirection();
            if (!_301.Redirect(url + (context.Request.Url.Query.Length > 0 ? "?" + HttpContext.Current.Request.Url.Query.Replace("?", "") : "")))
            {
                RewriteRules rewriteRules = RewriteRules.GetCurrentRewriteRules();
                rewrite = rewriteRules.GetMatchingRewrite(url);

                if (!string.IsNullOrEmpty(rewrite))
                {
                    context.RewritePath("~" + rewrite);
                }
                else
                {
                    rewrite = context.Request.Path + context.Request.Url.Query;
                }
            }

            string newFilePath = rewrite.IndexOf("?") > 0 ? rewrite.Substring(0, rewrite.IndexOf("?")) : rewrite;

            if (string.IsNullOrEmpty(newFilePath))
                newFilePath = "/404.aspx";

            try
            {
                return PageParser.GetCompiledPageInstance(newFilePath, context.Server.MapPath(newFilePath), context);
            }
            catch (Exception ex)
            {
                //HttpContext.Current.Response.Write(ex.StackTrace.ToString());
                return PageParser.GetCompiledPageInstance("/404.aspx", context.Server.MapPath("/404.aspx"), context);
            }
        }


        public void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}
